﻿using System;
using System.Windows.Threading;

namespace VXCompany.SilverlightLogging.MVVM.Models.SyncBehaviors
{
	public class PeriodicSync : SyncBehavior
	{
		private TimeSpan timeSpanBetween;

		/// <summary>
		/// Gets the DispatcherTimer.
		/// </summary>
		protected DispatcherTimer Timer { get; private set; }

		/// <summary>
		/// Creates new instance, sets timer.
		/// </summary>
		/// <param name="timeSpan"></param>
		public PeriodicSync(TimeSpan timeSpan)
		{
			Timer = new DispatcherTimer();
			Timer.Interval = timeSpan;
			Timer.Tick += (sender, ea) => BeginSynchronize();
			this.timeSpanBetween = timeSpan;
		}

		/// <summary>
		/// Gets behavior name.
		/// </summary>
		public override string Name
		{
			get { return string.Format("{0} ({1} mins)", base.Name, timeSpanBetween.TotalMinutes.ToString("F2")); }
		}

		/// <summary>
		/// Sets the timer for sync events.
		/// </summary>
		/// <param name="timeSpan"></param>
		protected override void StartImpl()
		{
			Timer.Start();
		}

		/// <summary>
		/// Stops timer.
		/// </summary>
		protected override void StopImpl()
		{
			Timer.Stop();
		}
	}
}
